/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.nio.http.server;

import cn.hermit.nio.core.RequestHandler;
import cn.hermit.nio.server.NioServer;
import cn.hermit.nio.http.Http;
import cn.hermit.nio.http.HttpException;

import java.io.IOException;
import java.net.InetAddress;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 30/5/2017
 */
public class HermitHttpServer extends NioServer implements HttpServer {

    private HttpRequestHandler requestHandler;

    public HermitHttpServer(int port) throws IOException {
        this(null, port, 0);
    }

    public HermitHttpServer(InetAddress hostAddress, int port) throws IOException {
        this(hostAddress, port, 0);
    }

    public HermitHttpServer(InetAddress hostAddress, int port, int workerCount) throws IOException {
        super(hostAddress, port, workerCount);
        requestHandler = new HttpRequestHandler();
    }

    @Override
    public RequestHandler getRequestHandler() {
        return requestHandler;
    }

    public HermitHttpServer router(HttpRouter router) {
        requestHandler.setRouter(router);
        return this;
    }

    public HermitHttpServer staticRoot(String staticRoot) {
        requestHandler.setStaticRoot(staticRoot);
        return this;
    }

    public HermitHttpServer enableCors(boolean enableCors) {
        requestHandler.enableCors(enableCors);
        return this;
    }

    @Override
    public HermitHttpServer refreshPageCache() {
        ResourceSoftCache.getInstance().clear();
        return this;
    }

    public static void main(String[] args) {
        try {
            SimpleHttpRouter router = new SimpleHttpRouter();
            router.bind(Http.Verb.GET.name(), "/hello/.*", new HttpHandler() {
                @Override
                public void handle(HttpRequest request,HttpResponse response) throws HttpException {
                    System.out.println(request.getHeader(Http.ACCEPT));
                    response.addHeader(Http.CONTENT_TYPE,Http.MEDIA_TYPE_TEXT_PLAIN);
                    byte[] body = "Hello HermitHttpServer!".getBytes();
                    response.addHeader(Http.CONTENT_LENGTH,body.length);
                    response.setBody(body);
                    System.out.println("Thread=>"+Thread.currentThread().getName());
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            new HermitHttpServer(9090).router(router).staticRoot("bak/web");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
